import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_plus/flutter_swiper_plus.dart';
import 'package:get/get.dart';
import 'package:remixicon/remixicon.dart';
import 'package:super_person_app/components/cache_widget.dart';
import 'package:super_person_app/constants/colors.dart';
import 'package:super_person_app/pages/home/home_state.dart';
import 'home_logic.dart';

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final logic = Get.find<HomeLogic>();
    final state = Get.find<HomeLogic>().state;

    return CacheWidget(
      child: SafeArea(
          child: Scaffold(
            backgroundColor: Colors.white,
            appBar: AppBar(
              centerTitle: true,
              elevation: 0,
              leading: _location(),
              title: _search(state.textEditingController.value),
              backgroundColor: Colors.white,
              actions: [
                IconButton(
                    onPressed: () => {},
                    padding: const EdgeInsets.all(0),
                    alignment: Alignment.center,
                    splashRadius: 30.w,
                    constraints: BoxConstraints(minWidth: 40.w, maxWidth: 40.w),
                    icon: Icon(
                      Remix.notification_2_line,
                      size: 18.sp,
                      color: const Color(0xff212121),
                    ))
              ],
              systemOverlayStyle: SystemUiOverlayStyle.light,
            ),
            body: ListView(
              children: [
                _swiper(),
                _gridWrapper(0, state, border: true),
                _gridWrapper(1, state),
                _firstNotice(),
                _news(),
              ],
            ),
          )),
    );
  }

  Widget _location() {
    return InkWell(
      onTap: () {},
      child: Container(
        padding: EdgeInsets.only(
          left: 10.w,
          right: 2.w,
        ),
        child: Row(
          children: [
            Icon(
              Remix.map_pin_2_fill,
              color: BasicColor.mainColor,
              size: 16.sp,
            ),
            const Text(
              "太原",
              style: TextStyle(color: Color(0xff222222), fontWeight: FontWeight.w600),
            )
          ],
        ),
      ),
    );
  }

  Widget _search(TextEditingController controller) {
    return Container(
      height: 36.h,
      padding: EdgeInsets.only(left: 4.w),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: const Color(0xffEDEDED), width: 0.5.w),
          borderRadius: BorderRadius.all(Radius.circular(10.w))),
      child: TextField(
        controller: controller,
        decoration: InputDecoration(
            focusColor: const Color(0xffB6B6B6),
            prefixIcon: Icon(Remix.search_line,
                color: const Color(0xffB6B6B6), size: 16.sp),
            prefixIconConstraints:
                BoxConstraints(maxWidth: 26.w, minWidth: 26.w),
            contentPadding: const EdgeInsets.only(top: 0, bottom: 0, left: 0),
            border: const OutlineInputBorder(
              borderSide: BorderSide(
                color: Colors.transparent,
              ),
            ),
            enabledBorder: const OutlineInputBorder(
              borderSide: BorderSide(
                color: Colors.transparent,
              ),
            ),
            disabledBorder: const OutlineInputBorder(
              borderSide: BorderSide(
                color: Colors.transparent,
              ),
            ),
            focusedBorder: const OutlineInputBorder(
              borderSide: BorderSide(
                color: Colors.transparent,
              ),
            ),
            hintText: "搜索商家、服务",
            hintStyle: TextStyle(
              fontSize: 14.sp,
              color: const Color(0xffB6B6B6),
            )),
      ),
    );
  }

  Widget _swiper() {
    return Container(
      padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 10.h),
      height: 130.h,
      child: Swiper(
        itemCount: 2,
        duration: 5,
        autoplay: true,
        scrollDirection: Axis.horizontal,
        viewportFraction: 1,
        autoplayDisableOnInteraction: true,
        scale: 1,
        pagination: SwiperPagination(
          alignment: Alignment.bottomRight,
          margin: const EdgeInsets.fromLTRB(0, 0, 0, 5),
          builder: DotSwiperPaginationBuilder(
              activeColor: BasicColor.mainColor,
              color: Colors.white,
              size: 6.w,
              activeSize: 6.w),
        ),
        itemBuilder: (BuildContext context, int index) {
          return Image.asset(
            "assets/image/2022-03-05_120637.png",
            fit: BoxFit.fill,
          );
        },
      ),
    );
  }

  Widget _gridWrapper(int index, HomeState state, {bool border = false}) {
    return Container(
      padding: EdgeInsets.only(top: 10.h, bottom: 10.h),
      margin: EdgeInsets.only(left: 16.w, right: 16.w),
      decoration: BoxDecoration(
        color: Colors.transparent,
        border: border
            ? Border(
                bottom:
                    BorderSide(color: const Color(0xffEDEDED), width: 0.5.w))
            : const Border.fromBorderSide(BorderSide.none),
      ),
      child: GridView(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 5,
          mainAxisSpacing: 0.9,
        ),
        children: [
          _gridItem(index, 0, state),
          _gridItem(index, 1, state),
          _gridItem(index, 2, state),
          _gridItem(index, 3, state),
          _gridItem(index, 4, state),
        ],
      ),
    );
  }

  Widget _gridItem(int index, int key, HomeState state) {
    List<Color> colors = index == 0 ? state.topColor[key] : [];
    String text = index == 0 ? state.topText[key] : state.bottomText[key];
    IconData icon = index == 0 ? state.topIcon[key] : state.bottomIcon[key];
    Color iconColor = index == 0 ? Colors.white : const Color(0xff212121);

    return InkWell(
      onTap: () {},
      child: Container(
        color: Colors.transparent,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 40.w,
              height: 40.w,
              margin: EdgeInsets.only(bottom: 6.h),
              decoration: BoxDecoration(
                  color: Colors.white,
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: colors.isNotEmpty
                        ? colors
                        : [Colors.white, Colors.white],
                  ),
                  borderRadius: BorderRadius.all(Radius.circular(50.w))),
              child: Icon(
                icon,
                color: iconColor,
                size: 20.sp,
              ),
            ),
            Text(text,
                style:
                    TextStyle(color: const Color(0xff181818), fontSize: 13.sp, fontWeight: FontWeight.w600))
          ],
        ),
      ),
    );
  }

  Widget _firstNotice() {
    return Container(
      padding: EdgeInsets.only(
        top: 10.h,
        bottom: 10.h,
        left: 16.w,
        right: 16.w,
      ),
      child: Container(
        height: 50.h,
        padding: EdgeInsets.all(10.w),
        decoration: BoxDecoration(
            color: const Color(0xffF6F6F6),
            borderRadius: BorderRadius.circular(4.w)),
        child: Row(
          children: [
            Container(
              width: 50.w,
              padding: EdgeInsets.only(right: 10.w),
              decoration: BoxDecoration(
                color: Colors.transparent,
                border: Border(
                    right: BorderSide(
                        color: const Color(0xffDDDDDD), width: 0.5.w)),
              ),
              alignment: Alignment.center,
              child: Text(
                "小区头条",
                textAlign: TextAlign.center,
                style: TextStyle(
                    color: BasicColor.mainColor,
                    fontSize: 13.sp,
                    fontWeight: FontWeight.bold,
                    fontStyle: FontStyle.italic),
              ),
            ),
            Expanded(
                child: Swiper(
              autoplay: true,
              scrollDirection: Axis.vertical,
              itemCount: 2,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  padding: EdgeInsets.only(left: 6.w),
                  height: 20.h,
                  child: Text(
                    "gopsutil是psutil的go语言版本实现，主要功能是获取系统上各项监控信息，包括不限于cpu,内存，磁盘，网络，进程，docker等等",
                    style: TextStyle(
                      color: const Color(0xff464647),
                      fontSize: 13.sp,
                      overflow: TextOverflow.ellipsis,
                      height: 1.3.h,
                    ),
                    maxLines: 2,
                  ),
                );
              },
            ))
          ],
        ),
      ),
    );
  }

  Widget _news() {
    return Container(
      margin: EdgeInsets.only(left: 16.w, right: 16.w, top: 10.h),
      child: Column(
        children: [
          _newsHeader(),
          _newsFooter(),
        ],
      ),
    );
  }

  Widget _newsHeader() {
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            "资讯聚焦",
            style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
          ),
          Row(
            children: [
              Text(
                "更多",
                style:
                    TextStyle(color: const Color(0xffA8A8A8), fontSize: 14.sp),
              ),
              Icon(
                Remix.arrow_right_s_line,
                color: const Color(0xffA8A8A8),
                size: 22.sp,
              )
            ],
          )
        ],
      ),
      padding: EdgeInsets.only(bottom: 10.h),
    );
  }

  Widget _newsFooter() {
    return Column(
      children: [
        _newsItem(
          "俄军按下“暂停键”？普京再次重申目标 北约再次拒绝乌克兰请求",
          "小央视频",
          "https://sf1-cdn-tos.toutiaostatic.com/img/user-avatar/6c2667b4e09670975055295b783e3901~300x300.image",
          picture: "https://p26.toutiaoimg.com/tos-cn-i-0004/a16e38b7a8da458483f6fb7055e22cdd~tplv-tt-cs0:640:360.jpg?from=feed&_iz=31826",
        ),
        _newsItem(
          "42岁至今单身：《人世间》这部剧过后，殷桃又该拿奖了吧",
          "书生不用剑",
          "https://sf1-cdn-tos.toutiaostatic.com/img/user-avatar/4c1258d0fa377358997244fd19884369~300x300.image",
          picture: "https://p9.toutiaoimg.com/tos-cn-i-qvj2lq49k0/c6a28ddb13284f12a2dbf41d24a3961f~tplv-tt-cs0:640:360.jpg?from=feed&_iz=31826",
        ),
        _newsItem(
          "火上热搜，鼓励年轻人少送外卖，多进工厂？",
          "财经主持人周媛",
          "https://sf3-cdn-tos.bdxiguastatic.com/img/user-avatar/2x_16c5c90cefe0b2b00af74a9d1b304ac1~300x300.image",
          picture: "https://p3.toutiaoimg.com/tos-cn-i-0026/7f0d84bf4cda48b8b17699eff3785660~tplv-tt-cs0:640:360.jpg?from=feed&_iz=31826",
        ),
        _newsItem(
          "baby庆祝离婚后首个生日，未修图照瘦到见胸骨，与精修图相差巨大",
          "娱乐emba",
          "https://p3.toutiaoimg.com/origin/user-avatar/39fcd269470489178b3abce9eb82978b",
          picture: "https://p6.toutiaoimg.com/origin/tos-cn-i-qvj2lq49k0/0ffc9d6632d6473ea5be2e1866e35527",
        ),
        _newsItem(
          "才开两年掉价13万，32万买20款奔驰glc真值！晚一步就被别人买走",
          "检车家",
          "https://p3.dcarimg.com/img/user-avatar/569472db572fc02eee0f474f1b4efabb~80x0.webp",
          picture: "https://p3.dcarimg.com/img/motor-img/5d888f95378c4e3eb079ae31e644b74f~500x0.webp",
        ),
        _newsItem(
          "驻美大使秦刚访问特斯拉美国工厂 与马斯克在model S上谈笑风生",
          "凤凰网科技",
          "http://d.ifengimg.com/q100/img1.ugc.ifeng.com/newugc/20180206/10/wemedia/0eb8e13206357563c36cbc1ffc0af323339f3a43_size16_w200_h200.png",
          picture: "https://x0.ifengimg.com/ucms/2022_10/59E61263F14990A45FB0CA8D578410CD2CEB78FB_size54_w650_h366.jpg",
        ),
        _newsItem(
          "如何征服老板娘？",
          "极速拍档",
          "https://p3.dcarimg.com/img/user-avatar/e1fd4ac7997532fbb03ed1788d562d3a~80x0.webp",
          picture:  "https://p3.dcarimg.com/img/pgc-image/0b8644eb7070455b94ae51a91784d50a~500x0.webp",
        ),
        _newsItem(
          "华亭宾馆望下去，曾经是一片农田",
          "解放日报",
          "http://pic.rmb.bdstatic.com/5b3b55e615eb50f79a4f51520e40bef3.jpeg?x-bce-process=image/resize,m_lfit,w_200,h_200&autime=40819",
          picture: "https://pics1.baidu.com/feed/f703738da9773912324455d55f907d11377ae2bc.jpeg?token=bd96faa76149b6b7de8e2bb840e28f1a",
        ),
      ],
    );
  }

  Widget _newsItem(String title, String target, String avatar, {String picture = ""}) {
    return Material(
      color: Colors.white,
      child: InkWell(
        child: Container(
          height: 80.h,
          padding: EdgeInsets.only(
              top: 10.h,
              bottom: 10.h,
          ),
          decoration: BoxDecoration(
            color: Colors.transparent,
            border: Border(
                top:
                BorderSide(color: const Color(0xffEDEDED), width: 0.5.w)),
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(title, maxLines: 2,style: TextStyle(
                          fontSize: 15.sp,
                          height: 1.2.h,
                          overflow: TextOverflow.ellipsis, fontWeight: FontWeight.w600
                      ),),
                      Row(
                        children: [
                          CircleAvatar(
                            radius: 8.w,
                            backgroundImage: CachedNetworkImageProvider(
                                avatar
                            ),
                          ),
                          SizedBox(width: 4.w,),
                          Text(target, style: TextStyle(
                              fontSize: 12.sp,
                              color: const Color(0xffB2B2B2)
                          ))
                        ],
                      )
                    ],
                  )),
              Container(
                width: 100.w,
                height: 80.h,
                margin: EdgeInsets.only(
                    left: 10.w
                ),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(4.w)),
                    image: DecorationImage(
                        fit: BoxFit.cover,
                        image: CachedNetworkImageProvider(
                          picture,
                        )
                    )
                ),
              )
            ],
          ),
        ),
        onTap: () {
          Get.toNamed("/home/news");
        },
      ),
    );
  }
}
